package com.lap.generator.application.assembler;

import com.lap.framework.tools.Named;
import com.lap.generator.commons.tools.TextUtil;
import com.lap.generator.config.EnvConfig;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.valueobject.FieldModel;
import com.lap.generator.infrastructure.query.meta.ColumnMeta;
import com.lap.generator.infrastructure.query.meta.TableMeta;
import lombok.experimental.UtilityClass;
import java.util.ArrayList;
import java.util.List;

@UtilityClass
public class ModelTransformer {

  public static TemplateModel transform(TableMeta tableMeta, EnvConfig config) {
    String className = config.getJdbcInfo().getTable().resolveName(tableMeta.getTableName());

    return TemplateModel.builder()
            .author(config.getBaseInfo().getAuthor())
            .version(config.getBaseInfo().getVersion())
            .basePackage(config.getPackName().getBasePackage())
            .tableName(tableMeta.getTableName())
            .tableComment(tableMeta.getTableComment())
            .module(TextUtil.resolverText(className))
            .className(Named.upperHump(className))
            .lowerName(Named.lowerHump(className))
            .mapping(Named.mappingUri(className))
            .fields(resolverFiledModel(Named.lowerHump(className), tableMeta, config))
            .build();
  }

  private static List<FieldModel> resolverFiledModel(
      String parentCode, TableMeta tableMeta, EnvConfig config) {

    List<FieldModel> fields = new ArrayList<>();
    for (ColumnMeta col : tableMeta.getColumns()) {
      FieldModel fieldModel =
          FieldModel.builder()
              .columnName(col.getColumnName())
              .columnType(col.getDataType())
              .fieldName(Named.lowerHump(col.getColumnName()))
              .modelType(col.getModelType())
              .comment(col.getComment())
              .nullable(col.isNullable())
              .build();

      fieldModel.addNotNullValidation(parentCode, config.getJdbcInfo().getTable().getExcludeField());
      fieldModel.addLengthValidation(parentCode, config.getJdbcInfo().getTable().getExcludeField());
      fieldModel.setDateField(config.getJdbcInfo().getTable().getExcludeField());
      fieldModel.setIgnoreField(config.getJdbcInfo().getTable().getExcludeField());
      fieldModel.setIgnoreInsert(config.getJdbcInfo().getTable().getIgnoreInsert());
      fieldModel.setIgnoreUpdate(config.getJdbcInfo().getTable().getIgnoreUpdate());

      fields.add(fieldModel);
    }
    return fields;
  }
}
